<?php
App::uses('CakeEmail', 'Network/Email');
class SecurityController extends AppController {
  public $helpers = array('Html', 'TWSForm');
  public $components = array('Session', 'Util');
  public $name = 'Security';

  function login() {
   $adminLoggedIn = $this->Session->read('User');
    if(isset($adminLoggedIn)) {
      $this->redirect('/admin');
    }
    $this->set('title_for_layout','Administration Login');
    if ($this->request->is('post')) {
      $this->loadModel('Login');
      $this->loadModel('User');
      $inputData = $this->_processRequestData($this->request);
      $inputData = $inputData['Security'];
      $login = array();
      $login['Login']=array();
      $login['Login']['email']=$inputData['email'];
      $login['Login']['password']=$inputData['password'];
      $test = sha1($login['Login']['password']);
      $this->Login->set($login);
      if($this->Login->validates()) {
        $user = $this->User->find("first", array('conditions' => array("User.email" => $login['Login']['email'], "User.password"=>sha1($login['Login']['password']))));
        if(!empty($user)) {
          if($user['User']['verified']!='Y') {
              //Sending verification email
              App::import('Helper', 'Html');
              $view = new View($this);
              $html = $view->loadHelper('Html');
              $url = FULL_BASE_URL.$html->url(array('action'=>'resendVerification',$user['User']['email']));
            $this->Session->setFlash('Your email address has not been verified by the system. An email would have been sent to '. $user['User']['email'] . ' with instructions on how to verify your account.<br/><br/>If you did not receive this email, you can <a href="'.$url.'">request to send this verification email</a> again.');
          } elseif ($user['User']['active']!='Y') {
            $this->Session->setFlash('Your account has been disabled. Please contact your site administrator to reactivate your account.');
          } else {
            $userRoles = array();
            //Getting User roles
            foreach($user['Role'] as $role){
              array_push($userRoles, $role['role_name']);
            }
            $user['UserRoles']=$userRoles;
            $this->Session->write('User',$user);
            $destinationUrl = $this->Session->read('destinationUrl');
            if (isset($destinationUrl)) {
              $this->Session->delete('destinationUrl');
              $this->redirect('/'.$destinationUrl);
            } else {
              $this->redirect("/admin");
            }
          }
        } else {
          $this->Session->setFlash('Invalid email address and password');
        }
      } else {
        $this->set('errors', $this->Passcode->validationErrors);
      }
    }
  }

  function resendVerification($account) {
    if(!empty($account)) {
      $this->loadModel('User');
      $user = $this->User->find("first", array('conditions' => array("User.email" =>$account)));
      if($user['User']['verified']!='Y') {
        $result = $this->_sendVerificationEmail($user);
        if($result){
          $this->Session->setFlash('An email was resent to verify your email account. Please wait a few minutes before checking for the email and follow the instructions to complete the registration process.' );
        } else {
          $this->Session->setFlash('An error occurred and your verification email could not be sent. Please try again.' );
        }
      } else {
        $this->Session->setFlash('Your account and email address has already been verified. You may log into the system.');
      }

      $this->render('login');
    } else {
     throw new NotFoundException();
    }
  }

  function admin_logout() {
    $this->Session->delete('User');
    $this->redirect("/");
  }

  function admin_resetPassword() {
    $this->layout = "admin";
    $this->set('title_for_layout','Reset admin password');
    if($this->request->is('post')) {
      $this->loadModel("User");
      $inputData = $this->_processRequestData($this->request);
      $user = $this->Session->read("User");
      $data= array("User" => array("id"=>$user['User']['id'],"password"=>sha1($inputData['Security']['password'])));
      $result=$this->User->save($data, false, array('password'));
      //$data["User"]["password"]=sha1($inputData['Security']['password']);
      //$result=$this->User->save(array("password"=>sha1($inputData['Security']['password'])));
      if(!empty($result)){
        $this->Session->setFlash('Your password was successfully reset.');
      } else {
        throw new Exception("An error has occurred and your password was not updated. Please try again!");
      }
    }
  }

  function register() {
    $this->set('title_for_layout','Admin Registration');
    if($this->request->is('post')){
      $this->loadModel('Passcode');
      $inputData = $this->_processRequestData($this->request);
      $data=array();
      $data['Passcode']=array();
      $data['Passcode']['id']=$inputData['Security']['passcode'];
      $this->Passcode->set($data);
      if($this->Passcode->validates()){
        $this->Session->write('Register', true);
        $this->redirect(array('action'=>'registerAdmin'));
      } else {
        $this->set('errors', $this->Passcode->validationErrors);
      }
    } else {
      $register = $this->Session->read('Register');
      if(isset($register)) {
        $this->redirect(array('action'=>'registerAdmin'));
      }
    }
  }

  function admin_passcode() {
    $this->layout = "admin";
    $this->set('title_for_layout','Change Passcode');
    $this->loadModel('Passcode');
    if($this->request->is('post')){  
      $inputData = $this->_processRequestData($this->request);
      $result = $this->Passcode->deleteAll(array("active"=>'Y'));
      if($this->Passcode->save(array('id' =>$inputData['Security']['passcode']),false ,array("id"))){
        $this->Session->setFlash('The passcode was successfully changed.');
      } else {
        $this->Session->setFlash('An error occurred and the passcode was not successfully changed. Please try again');
      }
    }
      $passcode = $this->Passcode->find('first');
      $this->set('passcode',$passcode);
  }

  function accountVerification() {
    $this->set('title_for_layout','Account verification');
    $account = $this->request->params['named']['id'];
    $verificationCode = $this->request->params['named']['auth'];
    if (empty($account) || empty($verificationCode)) {
      throw new NotFoundException('This is not a valid url');
    } else {
     $this->loadModel('User');
      $user = $this->User->find("first", array('conditions' => array("User.email" =>$account, "User.verification_code"=>$verificationCode)));
      if(empty($user)) {
        throw new NotFoundException('This is not a valid url');
      } else {
        if ($user['User']['verified']=='Y') {
          $this->Session->setFlash('This user account and email address has already been verified.');
        }else {
          //update account
          $this->User->id=$user['User']['id'];
          $this->User->saveField('verified','Y');
          $this->Session->setFlash('Your email address has been verified. You may now proceed to login.');
        }
      }
    }
    $this->render('login');
  }

  function registerAdmin() {
    $register = $this->Session->read('Register');
    if(isset($register)) {
      $this->set('title_for_layout','Admin Registration');
      if ($this->request->is('post')) {
        $this->loadModel('User');
        $inputData = $this->_processRequestData($this->request);
        $inputData = $inputData['Security'];
        $verificationCode = $this->_getRandomString(15);
        $data = array();
        $data['User']=array();
        $data['User']['first_name']=$inputData['first_name'];
        $data['User']['last_name']=$inputData['last_name'];
        $data['User']['email']=$inputData['email'];
        $data['User']['password']=$inputData['password'];
        $data['User']['verification_code']=$verificationCode;
        $this->User->set($data);
        if ($this->User->validates()) {
          //encrypt the password
          $data['User']['password']=sha1($data['User']['password']);
          if ($this->User->save($data, false)) {
            //setting up the role for the Admin
            $this->loadModel('UserRoles');
            $roleData=array();
            $roleData['UserRoles']=array();
            $roleData['UserRoles']['user_id']=$this->User->id;
            $roleData['UserRoles']['role_name']=Configure::read('App.adminRole');
            if ($this->UserRoles->save($roleData)) {
              //send email
              $this->_sendVerificationEmail($data);
              $this->Session->setFlash('Thank you for registering. In order to verify your email address, an email was sent to the address you specified. Please follow the instructions to complete the registration process.');
              $this->Session->delete('Register');
               $this->render('login');
            } else {
              $this->Session->setFlash('There was an error in registering your account. Can you please try again.');
            }
          }

        } else { //Validation did not occur
          $data['User']['password']="";
           $this->request->data['Security'] = $data['User'];
          $this->set('errors', $this->User->validationErrors);
        }
      } else {
        $register = $this->Session->read('Register');
        if(!isset($register )) {
          $this->redirect(array('action'=>'register'));
        }
      }
    } else {
       $this->redirect('register');
    }
  }

  function _sendVerificationEmail($user) {
    $retVal = false;
     if (is_array($user)){
      $data = $user;
      //Sending verification email
      App::import('Helper', 'Html');
      $view = new View($this);
      $html = $view->loadHelper('Html');
      $url = FULL_BASE_URL.$html->url(array('action'=>'accountVerification','id'=>$data['User']['email'],'auth'=>$data['User']['verification_code']));
      $email = new CakeEmail('tws');
      $email->to($data['User']['email'],$data['User']['first_name'].' '.$data['User']['last_name']);
      $email->subject("Verification for registration at the ".Configure::read('App.name'). " website");
      $email->template('activateLogin');
      $email->from(array(Configure::read('App.emailDefaultFrom')=>Configure::read('App.name')));
      $email->transport('Mail')->viewVars(array('name'=>$data['User']['first_name'].' '.$data['User']['last_name'],'clubName'=>Configure::read('App.name'),'verificationLink' => $url));
      $retVal = $email->send();
    }
    return $retVal;
  }

  function forgotPassword() {
    $this->set('title_for_layout','Forgot your password');
    if($this->request->is('post')){
     $this->loadModel('User');
     $inputData = $this->_processRequestData($this->request);
      $user = $this->User->find("first", array('conditions' => array("User.email" =>$inputData['Security']['email'])));
      if(!empty($user)) {
        $newPassword = $this->_getRandomString(5);
        $data= array("User" => array("id"=>$user['User']['id'],"password"=>sha1($newPassword)));
        $result=$this->User->save($data, false, array('password'));
        if(!empty($result)) {
          //send email
          $email = new CakeEmail('tws');
          $email->to($user['User']['email'],$user['User']['first_name'].' '.$user['User']['last_name']);
          $email->subject("Password request notification from the ".Configure::read('App.name'). " website");
          $email->template('forgotPassword');
          $email->from(array(Configure::read('App.emailDefaultFrom')=>Configure::read('App.name')));
          $email->transport('Mail')->viewVars(array('name'=>$user['User']['first_name'].' '.$user['User']['last_name'],'clubName'=>Configure::read('App.name'),'newPassword' => $newPassword));
          $retVal = $email->send();
          $this->Session->setFlash('Your password was successfully reset.');
        } else {
          CakeLog::error("The password was not successfully reset for user : [".$user['User']['id']."][".$user['User']['email']."]");
          $this->Session->setFlash('A problem occurred and your password was not successfully reset. Please try again.');
        }
      } else {
        $this->Session->setFlash('Please specify a valid Email.');
      }
      //reset password
      //send out email
    }
  }

  function _getRandomString($length = "")
  {
    $code = md5(uniqid(rand(), true));
    if ($length != "") return substr($code, 0, $length);
    else return $code;
  }

  }
  
  ?>